<?php
namespace app\service;
use think\Db;
class hzcityService
{

    const PRIKEY = 'MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJ9kkSjVy2HuSjFrByyQ7cULo2a268VQGcjsPH0/jMdT48l1vfmRWErljeAETPnJMttEeG1Ev9ll9A3KuSxT+u0mMRZe2UUy4Eeoayhw4d04tnoCgAaSWbpHMlfP0nKiRcssPxN49LeYizCMu8dRn23oDk4sp6AVEENIMw/Z6VeVAgMBAAECgYBQHa9s1BFXVvvJ3R8NAofQrCnknfriAYIEYOGCnue25O6wu1LS14CGnN10BRVf1AaQ+diCK7U2o61JJWVv54JO1zaaX/1ejP5YFklgHC5Kj3TXwTyALSqxgOmBmw16wtrLchfr0UrH9upW4VL335z+Mvr2XHYQBwv7Z0vOHYvboQJBANxYuV88m/Oc1T114CXf8a+ipHDwv1a2NJvVwSQU4P6TQ8oJm9SQlsrWXsSEWoIdcBWeXeM6nw4QV/gPHT+6unkCQQC5Lv671MhQjEvL5VcL9FZpIjO6I+uCRlBORmGmSMXecAaqZyiotxYqsIn58IY9+PVn3adRM6WSY4HQLHw9c/79AkEAxs1CCpwLdINmnToRzvo6+6T5SnDboSdpVcRIqv4vdWB2w/1hXCpL8pvxCssDQeu/abHlsZL9WFoElGlGkW4uuQJAaJls9Xe5NhYo8iC2zF/VN0lEYo3LhyhkT/JdUemlKoGoojPmuXXBJZfWN8Fuci7fny2KRsmfalKejpGyE5wjmQJAAxKOQ2ezrEAV9TlbSYdFOWwuvcoGZDLOl55hy1xsNPIkyyBvZ7FeLjPvphsMw4kFAes5TpnXe3keG4Lez94GRw==';//私钥字符串
    const PUBKEY = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCfZJEo1cth7koxawcskO3FC6NmtuvFUBnI7Dx9P4zHU+PJdb35kVhK5Y3gBEz5yTLbRHhtRL/ZZfQNyrksU/rtJjEWXtlFMuBHqGsocOHdOLZ6AoAGklm6RzJXz9JyokXLLD8TePS3mIswjLvHUZ9t6A5OLKegFRBDSDMP2elXlQIDAQAB';//公钥字符串
    
    const AccessID="A20190619152105";
    const URL="http://220.191.209.248:8990";
    const URL_PAY="http://parking.hzgxtc.com";//先离场后付费接口
    const URL_PAY_MQ="http://parking.hzgxtc.com:1883";//先离场后付费接口
    
//-----------------------停车数据接入接口(开始)------------------------------------
    //异常账单上报
    public function uploadAbnormalBill($arr){
        //拼接数据字符串
        $str='{'.
                '"data":{'.
                    '"billID": "'.$arr["billID"].'", '.
                    '"parkingCode": "'.$arr["parkingCode"].'", '.
                    '"uid": "'.$arr["uid"].'", '.
                    '"plateNo": "'.$arr["plateNo"].'", '.
                    '"plateColor": '.$arr["plateColor"].', '.
                    '"arriveTime": "'.$arr["arriveTime"].'", '.
                    '"endTime": "'.$arr["endTime"].'", '.
                    '"billTime": "'.$arr["billTime"].'", '.
                    '"shouldPay": '.$arr["shouldPay"].', '.
                    '"payStatus": '.$arr["payStatus"].
                '}'.
            '}';
        $url=self::URL_PAY."/api/v2/cp/uploadAbnormalBill";

        //密文
        $cipher=$this->pikeyEncrypt($str);
        //签名
        $sign=$this->getSign($cipher);
        $data=['accessID'=>self::AccessID,'cipher'=>$cipher,'sign'=>$sign];
        $result=$this->curlpost($url,$data);
        return $result;
    }
    //车辆签约信息查询
    public function getDeparturePayInfo($arr){
        //拼接数据字符串
        $str='{'.
                '"data":{'.
                    '"parkingCode": "'.$arr["parkingCode"].'", '.
                    '"plateNo": "'.$arr["plateNo"].'", '.
                    '"plateColor": '.$arr["plateColor"].
                '}'.
            '}';

        $url=self::URL_PAY."/api/v2/cp/getDeparturePayInfo";
        //密文
        $cipher=$this->pikeyEncrypt($str);
        //签名
        $sign=$this->getSign($cipher);
        $data=['accessID'=>self::AccessID,'cipher'=>$cipher,'sign'=>$sign];
        $result=$this->curlpost($url,$data);
        return $result;
    }
    
    
    public function confirmPayResult($arr){
        //更改数据库订单状态
        //查询车场
        $parkinginfo=Db::table("parkinglotinfo")->where("parking_id",$arr["parkingCode"])->find();
        if(!empty($parkinginfo)){
            $orderinfo=Db::table("car_order")
                    ->where("billID",$arr["billID"])
                    ->where("carPlateNo",$arr["plateNo"])
                    ->where("parkingNo",$parkinginfo["parkingNo"])
                    ->find();
            if($orderinfo["orderstatus"]!="SUCCESS"){
                Db::table("car_order")->where("order_id",$orderinfo["order_id"])->update(["orderstatus"=>"SUCCESS","notice_time"=>date("Y-m-d H:i:s")]);
            }
        }
        
        $str='{'.
                '"data":{'.
                    '"success":true,'.
                    '"requestId":'.$arr["requestId"].','.
                    '"params":{'.
                        '"plateNo":"'.$arr["plateNo"].'",'.
                        '"billID":"'.$arr["billID"].'",'.
                        '"billTime":"'.$arr["billTime"].'",'.
                        '"shouldPay":'.$arr["shouldPay"].','.
                        '"payStatus":'.$arr["payStatus"].','. 
                        '"actualPay":'.$arr["actualPay"].','.
                        '"dealTime":"'.$arr["dealTime"].'",'.
                        '"orderCode":"'.$arr["orderCode"].'",'.
                        '"paidType":'.$arr["paidType"].','.
                        '"payType":'.$arr["payType"].''.
                    '}'. 
                '}'.
            '}';
      
        $url=self::URL_PAY."/api/v2/cp/confirmPayResult";
        //密文
        $cipher=$this->pikeyEncrypt($str);
        //签名
        $sign=$this->getSign($cipher);
        $data=['accessID'=>self::AccessID,'cipher'=>$cipher,'sign'=>$sign];
        // return $data;
        $result=$this->curlpost($url,$data);
        return $result;
        
    }
    
    //停车场申请支付扣款
    public function applyPayment($arr){
        
        //拼接数据字符串
        $str='{'.
                '"data":{'.
                    '"parkingCode": "'.$arr["parkingCode"].'",'.
                    '"uid": "'.$arr["uid"].'",'.
                    '"plateNo":"'.$arr["plateNo"].'",'.
                    '"plateColor":'.$arr["plateColor"].','.
                    '"arriveTime": "'.$arr["arriveTime"].'",'.
                    '"endTime":"'.$arr["endTime"].'",'.
                    '"billID":"'.$arr["billID"].'",'.
                    '"billTime":"'.$arr["billTime"].'",'.
                    '"shouldPay":'.$arr["shouldPay"].','.
                    '"payStatus":'.$arr["payStatus"].','.
                    '"carStock":'.$arr["carStock"].','.
                '}'.
            '}';
        $url=self::URL_PAY."/api/v2/cp/applyPayment";
        //密文
        $cipher=$this->pikeyEncrypt($str);
        //签名
        $sign=$this->getSign($cipher);
        $data=['accessID'=>self::AccessID,'cipher'=>$cipher,'sign'=>$sign];
        $result=$this->curlpost($url,$data);
        return $result;
    }
    public function getPayResult($arr){
        //拼接数据字符串
        $str='{'.
                '"data":{'.
                    '"parkingCode": "'.$arr["parkingCode"].'", '.
                    '"plateNo": "'.$arr["plateNo"].'", '.
                    '"billID": "'.$arr["billID"].'"'.
                '}'.
            '}';
        $url=self::URL_PAY."/api/v2/cp/getPayResult";
        //密文
        $cipher=$this->pikeyEncrypt($str);
        //签名
        $sign=$this->getSign($cipher);
        $data=['accessID'=>self::AccessID,'cipher'=>$cipher,'sign'=>$sign];
        $result=$this->curlpost($url,$data);
        return $result;
    }
    public function confirmDeparturePayInfo($arr){
        $str='{'.
                '"data":{'.
                    '"success":true, '.
                    '"requestId":'.$arr["requestId"].', '.
                    '"params":{'.
                        '"plateNo":"'.$arr["plateNo"].'", '.
                        '"plateColor":"'.$arr["plateColor"].'", '.
                        '"parkingCode":"'.$arr["parkingCode"].'", '.
                        '"noSense":'.$arr["noSense"].', '.
                        '"moneyLimit":'.$arr["moneyLimit"].', '. 
                        '"departurePay":'.$arr["departurePay"].' '.
                    '}'. 
                '}'.
            '}';
        //    return $str;
        //file_put_contents($str,"confirmDeparturePayInfo.txt",FILE_APPEND);
        $url=self::URL_PAY."/api/v2/cp/confirmDeparturePayInfo";
        //密文
        $cipher=$this->pikeyEncrypt($str);
        //$t["cipher"]=$cipher;
        //签名
        $sign=$this->getSign($cipher);
        //$t["sign"]=$sign;
        $data=['accessID'=>self::AccessID,'cipher'=>$cipher,'sign'=>$sign];
        //return $data;
        $result=$this->curlpost($url,$data);
        return $result;
    }
    // 上传车辆到达记录（uploadCarInData）
    public function uploadCarInData($arr){
    	$parkingCode=$arr["parkingCode"];
    	$totalBerthNum="150";
    	$openBerthNum="130";
    	$freeBerthNum="70";
    	
    	$arr["parkingType"]="1";
        $arr["plateColor"]="1";
        //拼接数据字符串
        $str='{'.
                '"data":{'.
                    '"uid":"'.$arr["uid"].'",'.
                    '"arriveID":"'.$arr["arriveID"].'",'.
                    '"plateNo":"'.$arr["car_number"].'",'.
                    '"parkingCode": "'.$parkingCode.'",'.
                    '"gateNo":"'.$arr["gateNo"].'",'.
                    '"entryNum":"'.$arr["entryNum"].'",'.
                    '"totalBerthNum":"'.$totalBerthNum.'",'.
                    '"openBerthNum":"'.$openBerthNum.'",'.
                    '"freeBerthNum":"'.$freeBerthNum.'",'.
                    '"arriveTime":"'.$arr["arriveTime"].'",'.
                    '"parkingType":"'.$arr["parkingType"].'",'.
                    '"plateColor":"'.$arr["plateColor"].'",'.
                    '"uploadTime":"'.date('Y-m-d H:i:s').'"'.
                '}'.
            '}';
        //$t["str"]=$str;
        $path=dir(getcwd())->path.'/log/'.date('Ymd');
        if (! file_exists ( $path )) {
            mkdir ( "$path", 0777, true );
        }
        file_put_contents($path."/upload.txt",$str."\n",FILE_APPEND);
        
        $url=self::URL."/api/v2/cp/uploadCarInData";
        //密文
        $cipher=$this->pikeyEncrypt($str);
        //$t["cipher"]=$cipher;
        //签名
        $sign=$this->getSign($cipher);
        //$t["sign"]=$sign;
        $data=['accessID'=>self::AccessID,'cipher'=>$cipher,'sign'=>$sign];
        
        $result=$this->curlpost($url,$data);
        return $result;
        //$t["result"]=$result;
        //return $t;
    }

    //上传车辆离开记录uploadCarOutData
    public function uploadCarOutData($arr){
    	$parkingCode=$arr["parkingCode"];
    	$totalBerthNum=$arr["totalBerthNum"];
    	$openBerthNum=$arr["leftCounts"];
    	$freeBerthNum=$arr["leftCounts"];
    	
    	$arr["parkingType"]="1";
        $arr["plateColor"]="1";
        
        $arr["entryNum"]="1";

        $arr["endTime"]=date("Y-m-d H:i:s");
        //拼接数据字符串
        $str='{'.
                '"data":{'.
                    '"uid": "'.$arr["uid"].'", '.
                    '"endID": "'.$arr["uid"].'", '.
                    '"plateNo": "'.$arr["car_number"].'", '.
                    '"parkingCode": "'.$parkingCode.'", '.
                    '"gateNo": "'.$arr["gateNo"].'", '.
                    '"totalBerthNum": "'.$totalBerthNum.'", '.
                    '"openBerthNum": "'.$openBerthNum.'", '.
                    '"freeBerthNum": "'.$freeBerthNum.'", '.
                    '"arriveTime": "'.$arr["arriveTime"].'", '.
                    '"parkingType": "'.$arr["parkingType"].'", '.
                    '"endTime": "'.$arr["endTime"].'", '.
                    '"entryNum": "'.$arr["entryNum"].'", '.
                    '"outNum": "'.$arr["outNum"].'", '.
                    '"plateColor": "'.$arr["plateColor"].'", '.
                    '"uploadTime": "'.date('Y-m-d H:i:s').'"'.
                '}'.
            '}';

        
        $url=self::URL."/api/v2/cp/uploadCarOutData";
        //密文
        $cipher=$this->pikeyEncrypt($str);
        //签名
        $sign=$this->getSign($cipher);

        $data=['accessID'=>self::AccessID,'cipher'=>$cipher,'sign'=>$sign];
        $result=$this->curlpost($url,$data);
        return $result;
    }

    //上传停车场剩余开放泊位数（uploadParkingState）
    public function uploadParkingState($arr){
        //拼接数据字符串
        $str='{'.
                '"data":{'.
                    '"parkingCode": "'.$arr["parkingCode"].'", '.
                    '"totalBerthNum": "'.$arr["totalBerthNum"].'", '.
                    '"openBerthNum": "'.$arr["openBerthNum"].'", '.
                    '"freeBerthNum": "'.$arr["freeBerthNum"].'", '.
                    '"uploadTime": "'.$arr["uploadTime"].'"'.
                '}'.
            '}';

        $url=self::URL."/api/v2/cp/uploadParkingState";
        //密文
        $cipher=$this->pikeyEncrypt($str);
        //签名
        $sign=$this->getSign($cipher);

        $data=['accessID'=>self::AccessID,'cipher'=>$cipher,'sign'=>$sign];
        $result=$this->curlpost($url,$data);
        return $result;
    }
    //上传图片
    public function uploadPhoto($arr){
    	$parkingCode=$arr["parkingCode"];
    	$name=$arr["arriveID"]."_".$arr["type"].".jpg";
    	$uploadTime=date('Y-m-d H:i:s');
    	$photoID=$arr["arriveID"].$arr["type"];
        $arr["time"]=date("Y-m-d H:i:s");
        //拼接数据字符串
        $str='{'.
                '"data":{'.
                    '"uid": "'.$arr["uid"].'", '.
                    '"parkingCode": "'.$parkingCode.'", '.
                    '"photoID": "'.$photoID.'", '.
                    '"time": "'.$arr["time"].'", '.
                    '"type": "'.$arr["type"].'", '.
                    '"name": "'.$name.'", '.
                    '"uploadTime": "'.$uploadTime.'"'.
                '}'.
            '}';
        $url=self::URL."/api/v2/cp/uploadPhoto";
        //密文
        $cipher=$this->pikeyEncrypt($str);
        //签名
        $sign=$this->getSign($cipher);
        $data=['accessID'=>self::AccessID,'cipher'=>$cipher,'sign'=>$sign,'file'=>$arr["content"]];
        $result=$this->curlpost($url,$data);
        return $result;
    }

    //上传停车账单记录
    public function uploadPayRecord($arr){
        //拼接数据字符串
        $str='{'.
                '"data":{'.
                    '"billID": "'.$arr["billID"].'", '.
                    '"uid": "'.$arr["uid"].'", '.
                    '"plateNo": "'.$arr["plateNo"].'", '.
                    '"parkingCode": "'.$arr["parkingCode"].'", '.
                    '"chargeFee": '.$arr["chargeFee"].', '.
                    '"shouldPay": '.$arr["shouldPay"].', '.
                    '"actualPay": '.$arr["actualPay"].', '.
                    '"billTime": "'.$arr["billTime"].'", '.
                    '"dealTime": "'.$arr["dealTime"].'", '.
                    '"paidType": '.$arr["paidType"].', '.
                    '"payType": '.$arr["payType"].', '.
                    '"billWay": '.$arr["billWay"].', '.
                    '"uploadTime": "'.$arr["uploadTime"].'"'.
                '}'.
            '}';
        $url=self::URL."/api/v2/cp/uploadPayRecord";
        //密文
        $cipher=$this->pikeyEncrypt($str);
        //签名
        $sign=$this->getSign($cipher);
        $data=['accessID'=>self::AccessID,'cipher'=>$cipher,'sign'=>$sign];
        $result=$this->curlpost($url,$data);
        return $result;
    }
//-----------------------停车数据接入接口(结束)------------------------------------



    
    
    
//-------------------------------------------------    
    //公钥解密
    public function pubkeyDecrypt($data){
        $split = str_split(base64_decode($data), 128);  // 1024 bit  固定172
        $pubkey=$this->getPubKey();
        $crypto = '';
        foreach ($split as $chunk) {
            $isOkay = openssl_public_decrypt($chunk, $decryptData, $pubkey);  // base64在这里使用，因为172字节是一组，是encode来的
            if(!$isOkay){
                return false;
            }
            $crypto .= $decryptData;
        }
        return $crypto;
    }
    
    
    

    //私钥对字符串加密
    private function pikeyEncrypt($data){
        $encode_data="";
        $pi_key=$this->getPriKey();
        $split = str_split($data, 117);// 1024bit && OPENSSL_PKCS1_PADDING  不大于117即可
        $encode_data="";
        foreach ($split as $part) {
            $isOkay = openssl_private_encrypt($part, $en_data, $pi_key);
            if(!$isOkay){
                return false;
            }
            $encode_data .= $en_data;
        }
        $encode_data=base64_encode($encode_data);
        return $encode_data;
    }
    

    //私钥对密文签名
    private function getSign($string){
        $signature="";
        $pi_key=$this->getPriKey();
        openssl_sign($string, $signature, $pi_key,OPENSSL_ALGO_MD5);
        $signature=base64_encode($signature);
        return $signature;
    }
    //转换私钥为资源型数据
    private function getPriKey(){
        $private_key=$this->formatPriKey(hzcityService::PRIKEY);
        $pi_key = openssl_pkey_get_private($private_key);
        return $pi_key;
    }
    
    //转换私钥为资源型数据
    private function getPubKey(){
        $public_key=$this->formatPubKey(hzcityService::PUBKEY);
        $pi_key = openssl_pkey_get_public($public_key);
        return $pi_key;
    }
    //curl提交数据
    private function curlpost($url,$data){
        $headers = array('Content-Type: application/x-www-form-urlencoded');
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        //curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data)); // Post提交的数据包
        curl_setopt($curl, CURLOPT_TIMEOUT, 60); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            return 'Errno'.curl_error($curl);//捕抓异常
        }

        curl_close($curl);
        return $result;
    }

    private function formatPriKey($priKey) {
        $fKey = "-----BEGIN PRIVATE KEY-----\n";
        $len = strlen($priKey);
        for($i = 0; $i < $len; ) {
            $fKey = $fKey . substr($priKey, $i, 64) . "\n";
            $i += 64;
        }
        $fKey = $fKey . "-----END PRIVATE KEY-----";
        return $fKey;
    }
    private function formatPubKey($pubKey) {
        $fKey = "-----BEGIN PUBLIC KEY-----\n";
        $len = strlen($pubKey);
        for($i = 0; $i < $len; ) {
            $fKey = $fKey . substr($pubKey, $i, 64) . "\n";
            $i += 64;
        }
        $fKey = $fKey . "-----END PUBLIC KEY-----";
        return $fKey;
    }

}